import { sysLogin, sysProfile, sysUser } from '@/api/user.js'
import router, { syncRoutes } from '@/router/index.js'
import store from '@/store/index.js'
import { constantRoutes } from '@/router/index.js'
import { resetRouter } from '@/router/index.js'

const state = {
  token: '',
  username: '张三',
  userInfo: ''
}
const mutations = {
  setTokne(state, value) {
    state.token = value
  },
  setUserInfo(state, value) {
    state.userInfo = value
  },
  setUsername(state, value) {
    state.username = value
  },
  logout(state) {
    state.userInfo = ''
    resetRouter()
    state.token = ''
  }
}
const actions = {
  async saveToken({ commit }, value) {
    const res = await sysLogin(value)
    commit('setTokne', res.data)
  },
  async getUserInfo({ commit }) {
    const res = await sysProfile()
    const res2 = await sysUser(res.data.userId)
    const info = Object.assign({}, res.data, res2.data)
    commit('setUserInfo', info)

    const newArr = syncRoutes.filter((item) => {
      return info.roles.menus.includes(item.meta.name)
    })
    newArr.push({
      path: '/404',
      component: () => import('@/views/404'),
      hidden: true
    })
    // 在vuex中存储所有路由
    store.commit('routes/setRoutes', [...constantRoutes, ...newArr], {
      root: true
    })

    router.addRoutes(newArr)
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
